package com.jsgt.greekfire.ui.wallet.add

import android.app.Activity
import android.text.*
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.StringUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.PASSWORD_MIN_LENGTH
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.YTWallet
import com.jsgt.greekfire.common.util.YTWalletUtils
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.WalletBean
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import kotlinx.android.synthetic.main.activity_import_wallet_mnemonic.*
import kotlinx.android.synthetic.main.activity_import_wallet_mnemonic.edtContent
import kotlinx.android.synthetic.main.activity_import_wallet_mnemonic.txvOk
import org.web3j.crypto.MnemonicUtils
import org.web3j.utils.Numeric
import java.math.BigInteger

open class ImportWalletMnemonicActivity : BaseActivity() {
    open val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }

    private var wallet: YTWallet? = null
    private var coin: String? = null
    open var identityList: List<IdentityBean>? = null

    override fun needFitsSystemWindows(): Boolean {
        return false
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_import_wallet_mnemonic
    }

    override fun main() {
        setStatusBar(R.color.transparent, false, R.color.white)
        coin = intent.getStringExtra("coin")
        if (coin.isNullOrEmpty()) {
            finish()
        }
        title = String.format(getString(R.string.import_wallet_title), coin)

        initInputContent()
        cbPassword.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                edtPassword.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
            } else {
                edtPassword.transformationMethod =
                    PasswordTransformationMethod.getInstance()
            }
            endSelection(edtPassword)
        }
        cbPasswordRepeat.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                edtPasswordRepeat.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
            } else {
                edtPasswordRepeat.transformationMethod =
                    PasswordTransformationMethod.getInstance()
            }
            endSelection(edtPasswordRepeat)
        }

        txvOk.setOnClickListener {
            showProgress(true)
            txvOk.isEnabled = false
            if (!checkContent()) {
                txvOk.isEnabled = true
                showProgress(false)
                return@setOnClickListener
            } else if (edtPassword.text.isNullOrEmpty()) {
                ToastUtils.show(R.string.please_input_password)
                txvOk.isEnabled = true
                showProgress(false)
                return@setOnClickListener
            } else if (edtPasswordRepeat.text.isNullOrEmpty()) {
                ToastUtils.show(R.string.please_input_password_repeat)
                txvOk.isEnabled = true
                showProgress(false)
                return@setOnClickListener
            } else if (!TextUtils.equals(edtPassword.text, edtPasswordRepeat.text)) {
                ToastUtils.show(R.string.wallet_pwd_warning)
                txvOk.isEnabled = true
                showProgress(false)
                return@setOnClickListener
            } else if (edtPassword.text!!.toString().trim().length < PASSWORD_MIN_LENGTH) {
                ToastUtils.show(this, getString(R.string.wallet_safe_pwd_warning))
                txvOk.isEnabled = true
                showProgress(false)
                return@setOnClickListener
            } else {
                wallet = getWallet()
                if (wallet != null && !identityList.isNullOrEmpty()) {
                    identityList!!.forEach {
                        if (it.getPriKeyByAES() == wallet!!.getEcKeyPair().privateKey.toString()) {
                            ToastUtils.show(R.string.exist_wallet)
                            txvOk.isEnabled = true
                            showProgress(false)
                            return@setOnClickListener
                        }
                    }
                }
                save(wallet)
            }
        }

        walletViewModel.getAllIdentity()?.observe(this, Observer {
            identityList = it
            if (edtContent.text.isNotEmpty() && wallet != null) {
                it.forEach { it1 ->
                    if (it1.getPriKeyByAES() == wallet!!.getEcKeyPair().privateKey.toString()) { //判断私钥是否相同
                        val walletBean = WalletBean()
                        walletBean.key = coin
                        walletBean.identityId = it1.id
                        walletBean.address = wallet!!.address
                        walletBean.name = coin
                        walletBean.selection = 0
                        walletViewModel.addWallet(walletBean)
                        ToastUtils.show(R.string.import_success)
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                }
            }
        })
    }

    open fun save(wallet: YTWallet?) {
        try {
            if (wallet == null) {
                showProgress(false)
                ToastUtils.show(this, getString(R.string.input_help_word_error))
                txvOk.isEnabled = true
            } else {
                val identityBean = IdentityBean()
                identityBean.setMnemonicByAES(wallet.getMnemonic())
                identityBean.setPriKeyByAES(wallet.getEcKeyPair().privateKey.toString())
                identityBean.setPasswordByMd5(edtPassword.text.toString())
//                walletBean.identityName = walletName
                identityBean.backup = true
                if (edtPasswordTips.text.isNotEmpty()) {
                    identityBean.passwordTips = edtPasswordTips.text.toString()
                }
                walletViewModel.addIdentity(identityBean)
            }
        } catch (e: Exception) {
            showProgress(false)
            ToastUtils.show(this, getString(R.string.input_help_word_error))
            txvOk.isEnabled = true
        }
    }

    open fun getWallet(): YTWallet? {
        val helpWord = StringUtil.multiBlankTo1Space(edtContent.text.toString().trim())!!
        return YTWalletUtils.generateBip44Wallet(helpWord, null)
    }

    open fun checkContent(): Boolean {
        if (edtContent.text.isNullOrEmpty()) {
            ToastUtils.show(R.string.please_input_mnemonic)
            return false
        } else if (txvMnemonicError.visibility == View.VISIBLE) {
            ToastUtils.show(R.string.input_help_word_tips)
            return false
        } else if (!MnemonicUtils.validateMnemonic(
                StringUtil.multiBlankTo1Space(
                    edtContent.text.toString().trim()
                )!!
            )
        ) {
            ToastUtils.show(getString(R.string.input_help_word_error))
            return false
        }
        return true
    }

    open fun initInputContent() {
        edtContent.addTextChangedListener(object : TextWatcher {
            private var index = 0
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (TextUtils.isEmpty(s)) {
                    txvMnemonicError.visibility = View.GONE
                } else {
                    index = 0
                    val mnemonicList =
                        StringUtil.multiBlankTo1Space(s.toString().trim())!!.split(" ").reversed()
                    mnemonicList.forEach {
                        if (!MnemonicUtils.getWords().contains(it) &&
                            !(index == 0 && (it.isEmpty() || it.length == 1))
                        ) {
                            txvMnemonicError.visibility = View.VISIBLE
                            txvMnemonicError.text =
                                String.format(getString(R.string.input_help_word_tips1), it)
                            return@onTextChanged
                        }
                        index++
                    }
                    txvMnemonicError.visibility = View.GONE
                }

            }
        })
    }

    /**
     * 设置EditText游标至末尾
     */
    fun endSelection(editText: EditText) {
        val text: Spannable? = editText.text
        if (text != null) {
            Selection.setSelection(text, text.length)
        }
    }
}